﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TimeSheetReporting.Web.Service;
using TimeSheetReporting.Helper;
using TimeSheetReporting.Web.Model;

namespace TimeSheetReporting
{
    public partial class Home : Page
    {
        TimeSheetContext _dc;
        public Home()
        {
            InitializeComponent();
            gridEfforts.Loaded += new RoutedEventHandler(gridEfforts_Loaded);
        }

        void gridEfforts_Loaded(object sender, RoutedEventArgs e)
        {
            _dc = new TimeSheetContext();
            gridEfforts.ItemsSource = _dc.Efforts;

            MemberListProvider memberListProvider = LayoutRoot.Resources["memberListProvider"] as MemberListProvider;
            ProjectListProvider projectListProvider = LayoutRoot.Resources["projectListProvider"] as ProjectListProvider;

            memberListProvider.DomainContext = _dc;
            projectListProvider.DomainContext = _dc;

            _dc.Load<Effort>(_dc.GetEffortQuery());
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            Effort lastAddedEffort;
            if (_dc.Efforts.Count > 0)
            {
                lastAddedEffort = _dc.Efforts.ElementAt(_dc.Efforts.Count - 1);
            }
            else
            {
                lastAddedEffort = new Effort()
                    {
                        Date = DateTime.Today.Date
                    };
            }

            _dc.Efforts.Add(new Effort()
                {
                    Date = lastAddedEffort.Date,
                    Member = lastAddedEffort.Member,
                    Project = lastAddedEffort.Project,
                });
        }

        private void BtnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (gridEfforts.SelectedItem != null)
            {
                _dc.Efforts.Remove(gridEfforts.SelectedItem as Effort);
            }
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            _dc.SubmitChanges();
        }
    }
}